<?php

class Config {
  
  public function __construct(dataBaseConnection $connection) {
    $this->Connection = $connection;
  }
  
  public function GetAllConfig() {
    $queries = new mysqlqueries();
    $result = $this->Connection->query($queries->GetTable($queries->Configuration, null));
    $return = array("ScanTime"=>"","MaxThreads"=>"","Timeout"=>"","DHCPNetAddress"=>null,"DHCPAddress"=>"","SCPPath"=>"","Debug"=>"False","EnableNetwork"=>"","NetworkPath"=>"","NetworkPassword"=>"","NetworkUser"=>"");
    $dhcpNetAdresses = array();
    while ($row = mysqli_fetch_array($result)) {
      
      if($row["name"] == "DHCPNetAddress")
        array_push ($dhcpNetAdresses, $row["value"]);
      else
        $return[$row["name"]]=$row["value"];
    }
    $return["DHCPNetAddress"]=$dhcpNetAdresses;
    return $return;
  }
  
  public function deleteDHCPNet($net) {
    $queries = new mysqlqueries();
    $query = $queries->Remove($queries->Configuration, array("name","value"), array("DHCPNetAddress",$net));
    if(!$query)
    {
      return false;
    }
    $this->Connection->query($query);
    return true;
  }
  
  public function existEntry($entry) {
    $queries = new mysqlqueries();
    $query = $queries->GetIndex($queries->Configuration, $entry, "name", null);
    $result = $this->Connection->query($query);
    $exists = false;
    while ($row = mysqli_fetch_array($result)) {
      $exists = true;
    }
    return $exists;
  }
  
  public function AddDHCPNets($nets) {
    $args = array();
    foreach ($nets as $net) {
      if($net != "" && filter_var($net, FILTER_VALIDATE_IP))
        array_push($args, array("DHCPNetAddress",$net));
    }
    if(count($args)>0)
    {
      $queries = new mysqlqueries();
      $query=$queries->Add($queries->Configuration, $args);
      $this->Connection->query($query);
    }
  }
  
  public function Add($name,$value) {
    $queries=new mysqlqueries();
    $query =$queries->Add($queries->Configuration, array($name,$value));
    $this->Connection->query($query);
  }
  
  public function Update($name,$value) {
    $queries = new mysqlqueries();
    $query =$queries->Update($queries->Configuration, $value, $name, "value", "name");
    $this->Connection->query($query);
  }
  
  public function GetConfigEntryByName($name)
  {
    $queries = new mysqlqueries();
    $result = $this->Connection->query($queries->GetIndex($queries->Configuration, $name, "name", null));
    while ($row = mysqli_fetch_array($result)) {
      return $row["value"];
    }
    return false;
  }
  
  public function EntryExistsOrCreate($name, $value) {
    if($this->existEntry($name))
      $this->Update ($name, $value);
    else
      $this->Add ($name, $value);
  }
  public $Connection;
}
